package com.quartet.modules.vehicle.controller;


import com.quartet.api.ApiResult;
import com.quartet.api.PageResult;
import com.quartet.api.PageResultMap;
import com.quartet.modules.customer.service.TCustomerInfoService;
import com.quartet.modules.order.service.TOrderService;
import com.quartet.modules.service.aspect.AuthKeyValidated;
import com.quartet.modules.stock.service.TTerminalStockService;
import com.quartet.modules.vehicle.dto.*;
import com.quartet.modules.vehicle.service.TTerminalPositionInfoService;
import com.quartet.modules.vehicle.service.TVehicleInfoService;
import com.quartet.utils.BinaryUtil;
import com.quartet.utils.enums.RegionTypeEnum;
import com.quartet.utils.enums.TerminalOnLineEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 终端位置表(TVehiclePositionInfo)表控制层
 *
 * @author makejava
 * @since 2021-05-09 12:32:16
 */
@RestController
@RequestMapping("tTerminalPositionInfo")
@Api(tags = "业务：终端位置信息")
@Slf4j
public class TTerminalPositionInfoController {
    /**
     * 服务对象
     */
    @Resource
    private TTerminalPositionInfoService tTerminalPositionInfoService;

    /**
     * 服务对象
     */
    @Resource
    private TVehicleInfoService tVehicleInfoService;

    /**
     * 服务对象
     */
    @Resource
    private TCustomerInfoService tCustomerInfoService;

    /**
     * 服务对象
     */
    @Resource
    private TTerminalStockService tTerminalStockService;

    /**
     * 服务对象
     */
    @Resource
    private TOrderService tOrderService;

    /**
     * 分页查询所有终端位置信息
     *
     * @param tTerminalPositionInfoTrajectoryRequestDto 查询实体
     * @return 所有数据
     */
    @ApiOperation("分页查询所有终端位置信息")
    @PostMapping("/selectTerminalPositionTrajectoryPage")
//    @AuthKeyValidated("location")
    public ApiResult<PageResultMap<TTerminalPositionInfoResponseDto>> selectTerminalPositionTrajectoryPage(@RequestBody TTerminalPositionInfoTrajectoryRequestDto tTerminalPositionInfoTrajectoryRequestDto) {
        log.info("---------selectTerminalPositionTrajectoryPage begin, tTerminalPositionInfoTrajectoryRequestDto is {}----------", tTerminalPositionInfoTrajectoryRequestDto);
        if (CollectionUtils.isEmpty(tTerminalPositionInfoTrajectoryRequestDto.getQueryValue())) {
            return ApiResult.ok();
        }
        PageResultMap<TTerminalPositionInfoResponseDto> tTerminalPositionInfoResponseDtoList = tTerminalPositionInfoService.selectTerminalPositionTrajectoryPage(tTerminalPositionInfoTrajectoryRequestDto);
        return ApiResult.ok(tTerminalPositionInfoResponseDtoList);


//        Map<String, List<TTerminalPositionInfoResponseDto>> map = new HashedMap<>();
//        tVehiclePositionInfoRequestDto.getQueryValue().forEach(s -> {
//            QueryWrapper<TTerminalPositionInfo> queryWrapper = new QueryWrapper<>();
//            if (!ObjectUtils.isEmpty(tVehiclePositionInfoRequestDto.getCreateStartTime())) {
//                queryWrapper.lambda().ge(TTerminalPositionInfo::getCreateTime, tVehiclePositionInfoRequestDto.getCreateStartTime());
//            }
//            if (!ObjectUtils.isEmpty(tVehiclePositionInfoRequestDto.getCreateEndTime())) {
//                queryWrapper.lambda().le(TTerminalPositionInfo::getCreateTime, tVehiclePositionInfoRequestDto.getCreateEndTime());
//            }
//            List<TTerminalPositionInfo> tVehiclePositionInfoList = tTerminalPositionInfoService.list(queryWrapper);
//            List<TTerminalPositionInfoResponseDto> tVehiclePositionInfoResponseDtoList = tVehiclePositionInfoList.stream().map(tVehiclePositionInfo -> {
//                TTerminalPositionInfoResponseDto tTerminalPositionInfoResponseDto = BeanUtil.copyProperties(tVehiclePositionInfo, TTerminalPositionInfoResponseDto.class);
//                QueryWrapper<TVehicleInfo> queryWrapper1 = new QueryWrapper<>();
//                queryWrapper1.lambda().eq(TVehicleInfo::getEquipmentCode, tVehiclePositionInfo.getTerminalCode());
//                TVehicleInfo tVehicleInfo = tVehicleInfoService.getOne(queryWrapper1);
//                if (ObjectUtils.isEmpty(tVehicleInfo)) {
//                    return tTerminalPositionInfoResponseDto;
//                }
//                tTerminalPositionInfoResponseDto.setFlowCardNumber(tVehicleInfo.getFlowCardNumber());
//                tTerminalPositionInfoResponseDto.setCarNumber(tVehicleInfo.getCarNumber());
//                tTerminalPositionInfoResponseDto.setEquipmentCode(tVehicleInfo.getEquipmentCode());
//                return tTerminalPositionInfoResponseDto;
//            }).filter(tTerminalPositionInfoResponseDto -> filterVehiclePosition(s, tTerminalPositionInfoResponseDto)).collect(Collectors.toList());
//            map.put(s, tVehiclePositionInfoResponseDtoList);
//        });
//        return ApiResult.ok(map);
    }


    /**
     * 区域查终端接口
     *
     * @param tTerminalPositionInfoRegionLookupRequestDto 查询实体
     * @return 所有数据
     */
    @ApiOperation("区域查终端")
    @PostMapping("/selectTerminalPositionWithRegion")
//    @AuthKeyValidated("location")
    public ApiResult<List<TTerminalPositionInfoResponseDto>> selectTerminalPositionWithRegion(@RequestBody TTerminalPositionInfoRegionLookupRequestDto tTerminalPositionInfoRegionLookupRequestDto) {
        log.info("---------selectTerminalPositionWithRegion begin, tTerminalPositionInfoRegionLookupRequestDto is {}----------", tTerminalPositionInfoRegionLookupRequestDto);
//        if (StringUtils.isBlank(tTerminalPositionInfoRegionLookupRequestDto.getGeometry())) {
//            return ApiResult.ok(Collections.emptyList());
//        }
//        QueryWrapper<TTerminalPositionInfo> queryWrapper = new QueryWrapper<>();
//        if (!ObjectUtils.isEmpty(tTerminalPositionInfoRegionLookupRequestDto.getStartTime())) {
//            queryWrapper.lambda().ge(TTerminalPositionInfo::getEquipmentTime, tTerminalPositionInfoRegionLookupRequestDto.getStartTime());
//        }
//        if (!ObjectUtils.isEmpty(tTerminalPositionInfoRegionLookupRequestDto.getEndTime())) {
//            queryWrapper.lambda().le(TTerminalPositionInfo::getEquipmentTime, tTerminalPositionInfoRegionLookupRequestDto.getEndTime());
//        }
//
//        if (!ObjectUtils.isEmpty(tTerminalPositionInfoRegionLookupRequestDto.getSpeed())) {
//            queryWrapper.lambda().ge(TTerminalPositionInfo::getSpeed, tTerminalPositionInfoRegionLookupRequestDto.getSpeed());
//        }
//        String geometry = tTerminalPositionInfoRegionLookupRequestDto.getGeometry();
//        if (StringUtils.isBlank(geometry)) {
//            queryWrapper.lambda().orderByAsc(TTerminalPositionInfo::getCreateTime);
//        } else {
//            String sql = "and MBRContains(ST_GeomFromText('" + geometry + "'),point(longitude,latitude)) order by create_time";
//            queryWrapper.last(sql);
//        }
        if (RegionTypeEnum.CURRENT_AREA.getValue().equals(tTerminalPositionInfoRegionLookupRequestDto.getRegionType())) {
            List<TTerminalPositionInfoResponseDto> tTerminalPositionInfoResponseDtoList = tTerminalPositionInfoService.selectTerminalPositionWithRegion(tTerminalPositionInfoRegionLookupRequestDto);
            tTerminalPositionInfoResponseDtoList.stream().forEach(tTerminalPositionInfoResponseDto -> {
                //设置在线离线状态
                List<Integer> list = BinaryUtil.find1Cursor(tTerminalPositionInfoResponseDto.getStatus());
                if (list.contains(1)) {
                    tTerminalPositionInfoResponseDto.setOnlineStatus(TerminalOnLineEnum.ON_LINE.getValue());
                } else {
                    tTerminalPositionInfoResponseDto.setOnlineStatus(TerminalOnLineEnum.OFF_LINE.getValue());
                }
            });
            return ApiResult.ok(tTerminalPositionInfoResponseDtoList);
        } else {
            List<TTerminalPositionInfoResponseDto> tTerminalPositionInfoResponseDtoList = tTerminalPositionInfoService.selectTerminalPositionWithHistoryRegion(tTerminalPositionInfoRegionLookupRequestDto);
            List<TTerminalPositionInfoResponseDto> tVehiclePositionInfoResponseDtoList = new ArrayList<>();
            Map<String, List<TTerminalPositionInfoResponseDto>> map = tTerminalPositionInfoResponseDtoList.stream().collect(Collectors.groupingBy(TTerminalPositionInfoResponseDto::getTerminalCode));
            map.keySet().forEach(s -> {
//                TTerminalPositionInfoResponseDto tVehiclePositionInfoResponseDto = new TTerminalPositionInfoResponseDto();
                List<TTerminalPositionInfoResponseDto> vehiclePositionInfoList = map.get(s);
                //求出最大速度的实体
                TTerminalPositionInfoResponseDto tVehiclePositionInfoResponseDto = vehiclePositionInfoList.stream().max(Comparator.comparingDouble(TTerminalPositionInfoResponseDto::getSpeed)).orElse(null);
                tVehiclePositionInfoResponseDto.setRegionStartTime(vehiclePositionInfoList.get(0).getCreateTime());
                tVehiclePositionInfoResponseDto.setRegionEndTime(vehiclePositionInfoList.get(vehiclePositionInfoList.size() - 1).getCreateTime());
                tVehiclePositionInfoResponseDto.setServerTime(vehiclePositionInfoList.get(vehiclePositionInfoList.size() - 1).getCreateTime());
                Duration between = Duration.between(tVehiclePositionInfoResponseDto.getRegionStartTime(), tVehiclePositionInfoResponseDto.getRegionEndTime());
                tVehiclePositionInfoResponseDto.setRegionTimePeriod(between.toHours());
                tVehiclePositionInfoResponseDto.setMaxSpeed(tVehiclePositionInfoResponseDto.getSpeed());
                //设置在线离线状态
                List<Integer> list = BinaryUtil.find1Cursor(tVehiclePositionInfoResponseDto.getStatus());
                if (list.contains(1)) {
                    tVehiclePositionInfoResponseDto.setOnlineStatus(TerminalOnLineEnum.ON_LINE.getValue());
                } else {
                    tVehiclePositionInfoResponseDto.setOnlineStatus(TerminalOnLineEnum.OFF_LINE.getValue());
                }
                tVehiclePositionInfoResponseDtoList.add(tVehiclePositionInfoResponseDto);
            });
            return ApiResult.ok(tVehiclePositionInfoResponseDtoList);
        }
//        if (RegionTypeEnum.CURRENT_AREA.getValue().equals(tTerminalPositionInfoRegionLookupRequestDto.getRegionType())) {
//            List<TTerminalPositionInfoResponseDto> tVehiclePositionInfoResponseDtoList = tVehiclePositionInfoList.stream().map(tVehiclePositionInfo -> {
//                TTerminalPositionInfoResponseDto tVehiclePositionInfoResponseDto = BeanUtil.copyProperties(tVehiclePositionInfo, TTerminalPositionInfoResponseDto.class);
//                tVehiclePositionInfoResponseDto.setFlowCardNumber(tVehiclePositionInfo.getMobileNo());
//
//                QueryWrapper<TTerminalStock> queryWrapper1 = new QueryWrapper<>();
//                queryWrapper1.lambda().eq(TTerminalStock::getTerminalCode, tVehiclePositionInfo.getTerminalCode());
//                TTerminalStock tTerminalStock = tTerminalStockService.getOne(queryWrapper1);
//                if (!ObjectUtils.isEmpty(tTerminalStock)) {
//                    QueryWrapper<TOrder> queryWrapper2 = new QueryWrapper<>();
//                    queryWrapper2.lambda().eq(TOrder::getOrderCode, tTerminalStock.getOrderCode());
//                    TOrder tOrder = tOrderService.getOne(queryWrapper2);
//                    if (!ObjectUtils.isEmpty(tOrder)) {
//                        QueryWrapper<TCustomerInfo> queryWrapper3 = new QueryWrapper<>();
//                        queryWrapper3.lambda().eq(TCustomerInfo::getCustomerCode, tOrder.getCustomerCode());
//                        TCustomerInfo tCustomerInfo = tCustomerInfoService.getOne(queryWrapper3);
//                        if (!ObjectUtils.isEmpty(tCustomerInfo)) {
//                            tVehiclePositionInfoResponseDto.setCustomerName(tCustomerInfo.getCustomerName());
//                        }
//                    }
//                }
//                return tVehiclePositionInfoResponseDto;
//            }).collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TTerminalPositionInfoResponseDto::getTerminalCode))), ArrayList::new));
//            return ApiResult.ok(tVehiclePositionInfoResponseDtoList);
//        } else {
//            List<TTerminalPositionInfoResponseDto> tVehiclePositionInfoResponseDtoList = new ArrayList<>();
//            Map<String, List<TTerminalPositionInfo>> map = tVehiclePositionInfoList.stream().collect(Collectors.groupingBy(TTerminalPositionInfo::getTerminalCode));
//            map.keySet().forEach(s -> {
//                TTerminalPositionInfoResponseDto tVehiclePositionInfoResponseDto = new TTerminalPositionInfoResponseDto();
//                List<TTerminalPositionInfo> vehiclePositionInfoList = map.get(s);
//                //求出最大速度的实体
//                TTerminalPositionInfo tTerminalPositionInfo = vehiclePositionInfoList.stream().max(Comparator.comparingDouble(TTerminalPositionInfo::getSpeed)).orElse(null);
//                tVehiclePositionInfoResponseDto.setRegionStartTime(vehiclePositionInfoList.get(0).getCurrTime());
//                tVehiclePositionInfoResponseDto.setRegionEndTime(vehiclePositionInfoList.get(vehiclePositionInfoList.size() - 1).getCurrTime());
//                tVehiclePositionInfoResponseDto.setServerTime(vehiclePositionInfoList.get(vehiclePositionInfoList.size() - 1).getServerTime());
//                Duration between = Duration.between(tVehiclePositionInfoResponseDto.getRegionStartTime(), tVehiclePositionInfoResponseDto.getRegionEndTime());
//                tVehiclePositionInfoResponseDto.setRegionTimePeriod(between.toHours());
//                tVehiclePositionInfoResponseDto.setMaxSpeed(tTerminalPositionInfo.getSpeed());
//
//                tVehiclePositionInfoResponseDto.setFlowCardNumber(tTerminalPositionInfo.getMobileNo());
//                QueryWrapper<TTerminalStock> queryWrapper1 = new QueryWrapper<>();
//                queryWrapper1.lambda().eq(TTerminalStock::getTerminalCode, tTerminalPositionInfo.getTerminalCode());
//                TTerminalStock tTerminalStock = tTerminalStockService.getOne(queryWrapper1);
//                if (!ObjectUtils.isEmpty(tTerminalStock)) {
//                    QueryWrapper<TOrder> queryWrapper2 = new QueryWrapper<>();
//                    queryWrapper2.lambda().eq(TOrder::getOrderCode, tTerminalStock.getOrderCode());
//                    TOrder tOrder = tOrderService.getOne(queryWrapper2);
//                    if (!ObjectUtils.isEmpty(tOrder)) {
//                        QueryWrapper<TCustomerInfo> queryWrapper3 = new QueryWrapper<>();
//                        queryWrapper3.lambda().eq(TCustomerInfo::getCustomerCode, tOrder.getCustomerCode());
//                        TCustomerInfo tCustomerInfo = tCustomerInfoService.getOne(queryWrapper3);
//                        if (!ObjectUtils.isEmpty(tCustomerInfo)) {
//                            tVehiclePositionInfoResponseDto.setCustomerName(tCustomerInfo.getCustomerName());
//                        }
//                    }
//                }
//                tVehiclePositionInfoResponseDtoList.add(tVehiclePositionInfoResponseDto);
//            });


    }

//    /**
//     * 过滤车辆位置数据
//     *
//     * @param s
//     * @param tTerminalPositionInfoResponseDto
//     * @return
//     */
//    private boolean filterVehiclePosition(String s, TTerminalPositionInfoResponseDto tTerminalPositionInfoResponseDto) {
//        if (StringUtils.isBlank(tTerminalPositionInfoResponseDto.getCarNumber()) || StringUtils.isBlank(tTerminalPositionInfoResponseDto.getEquipmentCode())) {
//            return false;
//        }
//        if (StringUtils.isNotBlank(s)) {
//            if (tTerminalPositionInfoResponseDto.getEquipmentCode().contains(s) || tTerminalPositionInfoResponseDto.getCarNumber().contains(s)) {
//                return true;
//            } else {
//                return false;
//            }
//        }
//        return true;
//    }

    /**
     * 查询终端位置信息
     *
     * @param tTerminalPositionInfoRequestDto 查询实体
     * @return 所有数据
     */
    @ApiOperation("查询终端位置信息")
    @PostMapping("/selectTerminalPositionPage")
//    @AuthKeyValidated("location")
    public ApiResult<PageResult<TTerminalPositionInfoResponseDto>> selectTerminalPositionPage(@RequestBody TTerminalPositionInfoRequestDto tTerminalPositionInfoRequestDto) {
        log.info("---------selectTerminalPosition begin, tTerminalPositionInfoRequestDto is {}----------", tTerminalPositionInfoRequestDto);
//        if (TabTypeEnum.SELECT.getValue().equals(String.valueOf(tVehicleAlarmInfoRequestDto.getTabType()))) {
        PageResult<TTerminalPositionInfoResponseDto> tTerminalPositionInfoResponseDtoList = tTerminalPositionInfoService.selectTerminalPositionPage(tTerminalPositionInfoRequestDto);
//            return ApiResult.ok(tVehiclePositionInfoResponseDtoList);
//        } else if (TabTypeEnum.OVER_SPEED_ALARM.getValue().equals(String.valueOf(tVehicleAlarmInfoRequestDto.getTabType()))) {
//            List<TOverSpeedAlarmInfoResponseDto> tOverSpeedAlarmInfoResponseDtoList = tOverSpeedAlarmInfoService.selectOverSpeedAlarmList(tVehicleAlarmInfoRequestDto);
//            return ApiResult.ok(tOverSpeedAlarmInfoResponseDtoList);
//        } else if (TabTypeEnum.FATIGUE_DRIVING_ALARM.getValue().equals(String.valueOf(tVehicleAlarmInfoRequestDto.getTabType()))) {
//            List<TFatigueDrivingAlarmInfoResponseDto> tFatigueDrivingAlarmInfoResponseDtoList = tFatigueDrivingAlarmInfoService.selectFatigueDrivingAlarmList(tVehicleAlarmInfoRequestDto);
//            return ApiResult.ok(tFatigueDrivingAlarmInfoResponseDtoList);
//        } else if (TabTypeEnum.OTHER_ALARM.getValue().equals(String.valueOf(tVehicleAlarmInfoRequestDto.getTabType()))) {
//            List<TOtherAlarmInfoResponseDto> tOtherAlarmInfoResponseDtoList = tOtherAlarmInfoService.selectOtherAlarmList(tVehicleAlarmInfoRequestDto);
//            return ApiResult.ok(tOtherAlarmInfoResponseDtoList);
//        } else {
//            //获取状态表信息
//            List<TVehicleStatusInfoResponseDto> tVehicleStatusInfoResponseDtoList = tVehicleStatusInfoService.selectVehicleStatusInfo(tVehicleAlarmInfoRequestDto);
//            return ApiResult.ok(tVehicleStatusInfoResponseDtoList);
//        }
        return ApiResult.ok(tTerminalPositionInfoResponseDtoList);
    }

    /**
     * 查询终端位置轨迹坐标信息
     *
     * @param tTerminalPositionInfoTrajectoryRequestDto 查询实体
     * @return 所有数据
     */
    @ApiOperation("查询终端位置轨迹坐标信息")
    @PostMapping("/selectTerminalPositionTrajectoryCoordinatePage")
//    @AuthKeyValidated("location")
    public ApiResult<Map<String, List<TTerminalPositionTrajectoryCoordinateResponseDto>>> selectTerminalPositionTrajectoryCoordinate(@RequestBody TTerminalPositionInfoTrajectoryRequestDto tTerminalPositionInfoTrajectoryRequestDto) {
        log.info("---------selectTerminalPositionTrajectoryCoordinatePage begin, tTerminalPositionInfoTrajectoryRequestDto is {}----------", tTerminalPositionInfoTrajectoryRequestDto);
        Map<String, List<TTerminalPositionTrajectoryCoordinateResponseDto>> map = tTerminalPositionInfoService.selectTerminalPositionTrajectoryCoordinate(tTerminalPositionInfoTrajectoryRequestDto);
        return ApiResult.ok(map);
    }
}
